<!--
 * @Author: qm
 * @Date: 2021-04-16 09:18:04
 * @LastEditors: qm
 * @LastEditTime: 2021-04-16 09:18:04
 * @Description:
-->
<template>
  <div class="pickScanHeader">
    <van-nav-bar title="拣货扫描" left-text="返回" @click-left="onClickLeft"></van-nav-bar>
    <van-notice-bar v-if="pickTaskCode || bussinessType || orderType" :text="title" wrapable class="pickScanHeader-notice" />
    <div class="pick-scan-info">
      <van-cell>
        <div slot="title">
          <van-field readonly clickable v-model="formTitleItem.locationNoCode" placeholder="选择库位" @click="showLocationNo = true" />
          <van-popup v-model="showLocationNo" round position="bottom">
            <van-picker
              show-toolbar
              :columns="locationNoColumns"
              value-key="locationCode"
              @cancel="locationNoCancel"
              @confirm="locationNoConfirm"
            />
          </van-popup>
        </div>
        {{ formTitleItem.skuDesc }}
      </van-cell>
      <van-cell>
        <div slot="title">
          <van-field readonly clickable v-model="formTitleItem.sku" placeholder="选择sku" @click="showsku = true" />
          <van-popup v-model="showsku" round position="bottom">
            <van-picker ref="skuRef" show-toolbar :columns="skuColumns" value-key="sku" @cancel="skuCancel" @confirm="skuConfirm" />
          </van-popup>
        </div>
        {{ formTitleItem.qty }}
      </van-cell>
    </div>
    <div>
      <van-form :show-error-message="false">
        <van-field
          v-model="formItem.cartonNo"
          ref="cartonNo"
          id="cartonNo"
          name="拣货箱号"
          label="拣货箱号"
          placeholder="请扫描拣货箱号"
          @keyup.enter.native="cartonToLocationNo"
          @focus="cartonNoFocusClick"
          @click="cartonNoFocusClick"
          :readonly="cartonNoReadOnly"
          :disabled="!!cartonNo"
          :rules="[{required: true, message: '请扫描拣货箱号'}]"
        />
        <van-field
          v-model="formItem.locationNo"
          ref="locationNo"
          id="locationNo"
          name="库位"
          label="库位"
          placeholder="请扫描库位"
          @blur="locationNoToSku"
          @keyup.enter.native="$event.target.blur"
          @focus="locationNoFocusClick"
          @click="locationNoFocusClick"
          :readonly="locationNoReadOnly"
          clearable
          :rules="[{required: true, message: '请扫描库位'}]"
        />
        <van-field
          v-model="formItem.barCodeNo"
          ref="barCodeNo"
          id="barCodeNo"
          name="商品条码"
          label="商品条码"
          placeholder="请扫描商品条码"
          @keyup.enter.native="scanBarCodeNo"
          @focus="barCodeNoFocusClick"
          @click="barCodeNoFocusClick"
          :readonly="barCodeNoReadOnly"
          clearable
          :rules="[{required: true, message: '请扫描商品条码'}]"
        />
      </van-form>
      <div class="good-count">
        <span>拣货数量：1</span>
        <van-checkbox v-model="checked" icon-size="14" class="checkbox" shape="square" :disabled="totalCartons > 0 ? false : true">
          负数
        </van-checkbox>
      </div>
    </div>
    <van-cell-group>
      <van-row>
        <van-row type="flex">
          <van-col span="7">
            <van-cell-group>
              <van-cell title="商品" />
            </van-cell-group>
          </van-col>
          <van-col span="7">
            <van-cell-group>
              <van-cell title="库位" />
            </van-cell-group>
          </van-col>
          <van-col span="4">
            <van-cell-group>
              <van-cell title="数量" />
            </van-cell-group>
          </van-col>
          <van-col span="6">
            <van-cell-group>
              <van-cell title="拣货时间" />
            </van-cell-group>
          </van-col>
        </van-row>
      </van-row>
      <van-row type="flex" justify="center" align="center" class="pick-scan-list" v-for="(item, index) in scanLogVoList" :key="index">
        <van-col span="7">
          <span>{{ item.sku }}</span>
        </van-col>
        <van-col span="7">
          <span>{{ item.locationCode }}</span>
        </van-col>
        <van-col span="4" class="text-center">
          <span>{{ item.pickQty }}</span>
        </van-col>
        <van-col span="6" class="text-center">
          <span>{{ item.createdDate }}</span>
        </van-col>
      </van-row>
    </van-cell-group>
    <van-tabbar>
      <van-tabbar-item icon="cart-o" @click="onClickDetail">
        详 情
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import {
  getLocationNoData,
  getSkuData,
  insertPickingLog,
  deletePickLog,
  getPickLogByRefresh,
  computePickedQtySum,
  formatNumberToDateTime
} from "@/api/pickScan/pickTask";
export default {
  name: "pickScanHeader",
  computed: {
    ...mapGetters("scanner", ["pdaScanData"]),
    ...mapGetters("user", ["userData"]),
    title() {
      return this.pickTaskCode + " - " + this.bussinessType + (this.orderType ? " - " + this.orderType : "");
    }
  },
  watch: {
    "pdaScanData": {
      handler(data) {
        let input = document.activeElement.id;
        if (input == "cartonNo") {
          this.formItem.cartonNo = data.data;
          this.cartonToLocationNo();
        } else if (input == "locationNo") {
          this.formItem.locationNo = data.data;
          this.locationNoToSku();
        } else if (input == "barCodeNo") {
          this.formItem.barCodeNo = data.data;
          this.scanBarCodeNo();
        }
      },
      deep: true
    },
    "formTitleItem.locationNoCode"() {
      this.checkLocaltionNo();
    },
    "$route": {
      handler(route) {
        if (route.name === "pickScanHeader") {
          this.pickTaskCode = this.$route.params.pickTaskCode;
          this.pickTaskId = this.$route.params.pickTaskId;
          this.bussinessType = this.$route.params.bussinessType;
          this.orderType = this.$route.params.orderType;
          this.cartonNo = this.$route.params.cartonNo;
          this.formItem.cartonNo = this.cartonNo;
          this.shelvesName = this.$route.params.shelvesName;
          this.getLocationNoDataList();
          this.$nextTick(() => {
            this.check();
          });
        }
      }
    },
    "deep": true
  },

  created() {
    if (this.$route.params.pickTaskId != undefined) {
      this.pickTaskCode = this.$route.params.pickTaskCode;
      this.pickTaskId = this.$route.params.pickTaskId;
      this.bussinessType = this.$route.params.bussinessType;
      this.orderType = this.$route.params.orderType;
      this.cartonNo = this.$route.params.cartonNo;
      this.formItem.cartonNo = this.cartonNo;
      this.shelvesName = this.$route.params.shelvesName;
      this.getLocationNoDataList();
      this.$nextTick(() => {
        this.check();
      });
    }
  },

  data() {
    return {
      //  库位
      locationNoColumns: [],
      //  sku
      skuColumns: [],
      //  拣货箱号
      showStorer: false,
      //  sku
      showsku: false,
      //
      showLocationNo: false,
      // 拣货箱号是否不可选
      cartonNoDisabled: false,
      // 拣货箱号是否只读
      cartonNoReadOnly: false,
      locationNoReadOnly: false,
      barCodeNoReadOnly: false,
      // 是否不可选
      Disabled: false,
      // 是否只读
      ReadOnly: false,
      //  barcode是否只读
      BarCodeReadOnly: false,
      // 数量是否不可选
      scanDisabled: true,
      // 数量是否只读
      scanReadonly: true,
      // 勾选标识
      checked: false,
      //   负数判断，初始为0，扫描数量>0才允许勾选负数
      totalCartons: 0,
      //  抬头 库位，SKU，商品名称，数量
      formTitleItem: {
        locationNo: "",
        locationNoCode: "",
        sku: "",
        skuDesc: "",
        qty: "",
        pickedQty: "0",
        allocQty: "0"
      },
      //   拣货箱号，库位，商品条码参数
      formItem: {
        cartonNo: "",
        locationNo: "",
        barCodeNo: "",
        sku: "",
        skuDesc: ""
      },
      //   扫描商品信息列表
      scanLogVoList: [],
      qty: 1,
      //  箱号ID
      cartonIdNow: "0",
      //  拣货任务号
      pickTaskCode: "",
      //  拣货任务ID
      pickTaskId: "",
      //   业务类型
      bussinessType: "",
      orderType: "",
      cartonNo: "",
      //  货架
      shelvesName: "",
      skuIndex: ""
    };
  },

  methods: {
    checkLocaltionNo() {
      if (this.formItem.locationNo && this.formTitleItem.locationNoCode.trim() !== this.formItem.locationNo.trim()) {
        this.formItem.locationNo = "";
        this.$refs["locationNo"].validate();
      }
      this.check();
    },
    //  返回
    onClickLeft() {
      this.$router.push({
        name: "b2cpickScan"
      });
    },

    //  获取库位列表信息
    getLocationNoDataList() {
      if (this.$route.params.pickTaskId === undefined) {
        console.log("无拣货单ID");
      } else {
        this.pickTaskCode = this.$route.params.pickTaskCode;
        this.pickTaskId = this.$route.params.pickTaskId;
        this.bussinessType = this.$route.params.bussinessType;
        this.shelvesName = this.$route.params.shelvesName;
        getLocationNoData(this.pickTaskId, this.userData.sysUserLoginName)
          .then(response => {
            if (response.data.status) {
              this.locationNoColumns = response.data.data;
              this.formItem.storerId = this.locationNoColumns[0].locationId;
              this.formItem.storerName = this.locationNoColumns[0].locationCode;
              this.formTitleItem.locationNo = this.locationNoColumns[0].locationId;
              this.formTitleItem.locationNoCode = this.locationNoColumns[0].locationCode;
              this.getSkuDataList();
            }
          })
          .catch(() => {
            this.$toast.fail("请求出错！");
          });
      }
    },

    //  库位下拉取消
    locationNoCancel() {
      this.showLocationNo = false;
    },

    //  库位下拉确定
    locationNoConfirm(value) {
      this.formTitleItem.locationNo = value.locationId;
      this.formTitleItem.locationNoCode = value.locationCode;
      this.showLocationNo = false;
      this.getSkuDataList();
    },

    //  拉取sku信息
    getSkuDataList() {
      getSkuData(this.pickTaskId, this.formTitleItem.locationNo, this.userData.sysUserLoginName)
        .then(response => {
          if (response.data.status) {
            this.skuColumns = response.data.data;
            this.formItem.sku = this.skuColumns[0].sku;
            this.formItem.skuDesc = this.skuColumns[0].skuDesc;
            this.formTitleItem.sku = this.skuColumns[0].sku;
            this.formTitleItem.skuDesc = this.skuColumns[0].skuDesc;
            this.formTitleItem.pickedQty = this.skuColumns[0].sumPickedQty;
            this.formTitleItem.allocQty = this.skuColumns[0].sumAllocQty;
            this.getScanDetailData();
            this.findQty();
            //   this.formTitleItem.qty = this.formTitleItem.pickedQty +"/" + this.formTitleItem.allocQty;
          } else {
            this.$toast.fail(response.data.message);
          }
        })
        .catch(() => {
          this.$toast.fail("请求出错！");
        });
    },

    //  sku下拉取消
    skuCancel() {
      this.showsku = false;
    },

    //  sku下拉确定
    skuConfirm(value) {
      this.formTitleItem.sku = value.sku;
      this.formTitleItem.skuDesc = value.skuDesc;
      (this.formTitleItem.pickedQty = value.sumPickedQty),
        (this.formTitleItem.allocQty = value.sumAllocQty),
        (this.formTitleItem.qty = value.sumPickedQty + "/" + value.sumAllocQty);
      this.showsku = false;
      this.formItem.barCodeNo = "";
      this.$nextTick(() => {
        this.$refs["barCodeNo"].focus();
      });
      this.getScanDetailData();
      this.findQty();
    },

    //  sku下拉确定
    skuChange() {
      this.formTitleItem.sku = this.skuColumns[this.skuIndex].sku;
      this.formTitleItem.skuDesc = this.skuColumns[this.skuIndex].skuDesc;
      (this.formTitleItem.pickedQty = this.skuColumns[this.skuIndex].sumPickedQty),
        (this.formTitleItem.allocQty = this.skuColumns[this.skuIndex].sumAllocQty),
        (this.formTitleItem.qty = this.skuColumns[this.skuIndex].sumPickedQty + "/" + this.skuColumns[this.skuIndex].sumAllocQty);
      this.showsku = false;
      this.formItem.barCodeNo = "";
      this.$nextTick(() => {
        this.$refs["barCodeNo"].focus();
      });
      this.getScanDetailData();
      this.findQty();
    },
    //  输入拣货箱号回车
    cartonToLocationNo() {
      if (this.formItem.cartonNo == "") {
        this.$toast.fail("请输入有效拣货箱号！");
        this.$nextTick(() => {
          this.$refs.cartonNo.focus();
          document.querySelector("#cartonNo .ivu-input").select();
        }, 100);
      } else {
        this.cartonNoDisabled = true;
        this.check();
      }
    },
    //  输入拣货箱号回车
    locationNoToSku() {
      if (this.formItem.locationNo) {
        // 如果扫描的库位 跟 当前选择的库位不一致 则 清空扫描库位值
        if (this.formTitleItem.locationNoCode.trim() !== this.formItem.locationNo.trim()) {
          this.formItem.locationNo = "";
          this.$refs["locationNo"].focus();
        } else {
          this.check();
        }
      }
    },
    // 检验箱号 库位 条码那个字段值为空，若为空，则获取焦点
    check() {
      let arry = ["cartonNo", "locationNo", "barCodeNo"];
      let flag = true;
      arry.forEach(item => {
        if (flag && !this.formItem[item]) {
          this.$nextTick(() => {
            this.$refs[item].focus();
          });
          flag = false;
        }
      });
    },
    locationNooFocusClick() {
      this.ReadOnly = true;
      setTimeout(() => {
        this.ReadOnly = false;
      }, 200);
    },

    //  扫描Barcode
    scanBarCodeNo() {
      // 判断箱号和库位是否有值，如果存在没有值的则将焦点自动聚焦到没有值的位置
      if (!this.formItem["cartonNo"].trim() || !this.formItem["locationNo"].trim()) {
        this.$refs["locationNo"].validate();
        this.check();
        this.formItem.barCodeNo = "";
        return;
      }
      if (Number(this.formTitleItem.allocQty) - Number(this.formTitleItem.pickedQty) <= 0 && !this.checked) {
        this.$toast.fail("该SKU已全扫描，请选择下一个未完成扫描的SKU！");
        this.$nextTick(() => {
          this.$refs.barCodeNo.focus();
          this.formItem.barCodeNo = "";
        }, 100);
      } else {
        let data = {
          storerId: this.$root.storerWarehouseBrand.storerId,
          warehouseId: this.$root.storerWarehouseBrand.warehouseId,
          brandId: this.$root.storerWarehouseBrand.brandId,
          pickTaskId: this.pickTaskId,
          pickTaskCode: this.pickTaskCode,
          sku: this.formTitleItem.sku,
          cartonNo: this.formItem.cartonNo,
          scanValue: this.formItem.barCodeNo,
          locationCode: this.formItem.locationNo,
          locationId: this.formTitleItem.locationNo,
          scanQty: this.qty,
          userCode: this.userData.sysUserLoginName,
          cartonId: this.cartonIdNow
        };
        if (!this.checked) {
          insertPickingLog(data)
            .then(response => {
              if (response.data.status) {
                let res = response.data.data;
                // 任务关闭
                if (res.isClose) {
                  this.$toast.success(response.data.message);
                  this.$router.push({
                    name: "b2cpickScan"
                  });
                  return;
                }
                this.cartonIdNow = response.data.data.cartonId;
                this.formTitleItem.locationNo = res.locationId;
                // 更新库位号
                this.formTitleItem.locationNoCode = res.locationCode;
                // 更新sku
                this.formTitleItem.sku = res.sku;
                this.formTitleItem.qty = response.data.data.pickedQty + "/" + this.formTitleItem.allocQty;
                if (Number(this.formTitleItem.allocQty) - Number(response.data.data.pickedQty) <= 0) {
                  if (this.skuColumns.length > 1) {
                    for (let index1 = 0; index1 < this.skuColumns.length; index1++) {
                      if (this.skuColumns[index1].sku == response.data.data.sku) {
                        this.skuIndex = index1;
                        this.skuChange();
                        break;
                      }
                    }
                  }
                }
                this.getScanDetailData();
                this.findQty();
              } else {
                this.$toast.fail(response.data.message);
              }
              this.formItem.barCodeNo = "";
            })
            .catch(() => {
              this.$toast.fail("请求出错！");
              this.formItem.barCodeNo = "";
            });
        } else {
          deletePickLog(data)
            .then(response => {
              if (response.data.status) {
                this.getScanDetailData();
                this.findQty();
              } else {
                this.$toast.fail(response.data.message);
              }
              this.formItem.barCodeNo = "";
            })
            .catch(() => {
              this.$toast.fail("请求出错！");
              this.formItem.barCodeNo = "";
            });
        }
      }
    },

    //  获取扫描详情信息
    getScanDetailData() {
      getPickLogByRefresh(
        this.$root.storerWarehouseBrand.storerId,
        this.$root.storerWarehouseBrand.warehouseId,
        this.$root.storerWarehouseBrand.brandId,
        this.pickTaskId,
        this.cartonIdNow !== "0" ? this.cartonIdNow : this.$route.params.cartonId || "0"
      )
        .then(response => {
          if (response.data.status) {
            this.scanLogVoList = response.data.data;
            if (this.scanLogVoList.length > 0) {
              for (let index = 0; index < this.scanLogVoList.length; index++) {
                this.scanLogVoList[index].createdDate = formatNumberToDateTime(this.scanLogVoList[index].createdDate);
              }
            }
          } else {
            this.scanLogVoList = [];
          }
        })
        .catch(() => {
          this.$toast.fail("请求出错！");
        });
    },

    //  汇总当前sku下的拣货数量
    findQty() {
      computePickedQtySum(
        this.$root.storerWarehouseBrand.storerId,
        this.$root.storerWarehouseBrand.warehouseId,
        this.$root.storerWarehouseBrand.brandId,
        this.pickTaskId,
        this.formTitleItem.locationNo,
        this.formTitleItem.sku
      )
        .then(response => {
          if (response.data.status) {
            this.totalCartons = response.data.data.pickedQty;
            this.formTitleItem.pickedQty = response.data.data.pickedQty;
            this.formTitleItem.qty = response.data.data.pickedQty + "/" + this.formTitleItem.allocQty;
            if (Number(response.data.data.pickedQty) < 1) {
              this.totalCartons = 0;
            }
            this.checked = false;
          } else {
            this.formTitleItem.pickedQty = 0;
            this.checked = false;
            this.totalCartons = 0;
            this.formTitleItem.qty = "0/" + this.formTitleItem.allocQty;
          }
        })
        .catch(() => {
          this.$toast.fail("请求出错！");
        });
    },

    //  查看详情
    onClickDetail() {
      if (this.pickTaskCode == "") {
        this.$toast.fail("请先去领取任务！");
      } else {
        this.$router.push({
          name: "b2cPickickScanDetail",
          query: {
            pickTaskCode: this.pickTaskCode,
            pickTaskId: this.pickTaskId,
            skuCartonNo: this.formItem.skuCartonNo,
            bussinessType: this.bussinessType,
            shelvesName: this.shelvesName
          },
          params: {
            orderType: this.orderType,
            cartonNo: this.cartonNo,
            cartonId: this.$route.params.cartonId
          }
        });
      }
    },
    cartonNoFocusClick() {
      this.cartonNoReadOnly = true;
      setTimeout(() => {
        this.cartonNoReadOnly = false;
      }, 200);
    },
    locationNoFocusClick() {
      this.locationNoReadOnly = true;
      setTimeout(() => {
        this.locationNoReadOnly = false;
      }, 200);
    },
    barCodeNoFocusClick() {
      this.barCodeNoReadOnly = true;
      setTimeout(() => {
        this.barCodeNoReadOnly = false;
      }, 200);
    }
  }
};
</script>

<style scoped lang="less">
.pickScanHeader {
  /deep/ .pickScanHeader-notice.van-notice-bar {
    padding: 4px 16px;
    line-height: 20px;
  }
  .good-count {
    font-size: 14px;
    padding: 10px 16px;
    display: flex;
    .checkbox {
      font-size: 14px;
      margin-left: 40px;
    }
  }
  .pick-scan-info {
    border-bottom: 1px dotted #ebedf0;
    /deep/ .van-cell {
      padding: 4px 16px;
      &::after {
        border-bottom: 0;
      }
    }
    /deep/ .van-cell__value {
      color: #333;
    }
    /deep/ .van-field {
      padding: 0;
      &::after {
        border-bottom: 0;
      }
    }
  }
  .pick-scan-list {
    /deep/ .van-col {
      font-size: 14px;
      padding: 8px 4px;
      span {
        word-break: break-all;
        word-break: break-word;
      }
    }
    .text-center {
      text-align: center;
    }
  }
}
</style>
